﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Data;

namespace App4.Controls
{
    class NullableCheckbox : CheckBox
    {
        public NullableCheckbox()
        {
            this.DefaultStyleKey = typeof(CheckBox);
            // setup
            var binding = new Binding
            {
                Path = new PropertyPath("IsChecked"),
                Mode = BindingMode.TwoWay,
                Source = this,
            };
            this.SetBinding(NullableCheckbox.InternalStateProperty, binding);
            this.IsChecked2 = null;// (bool?)this.InternalState;
        }

        private object InternalState
        {
            get { return (object)GetValue(InternalStateProperty); }
            set { SetValue(InternalStateProperty, value); }
        }
        public static readonly DependencyProperty InternalStateProperty =
            DependencyProperty.Register("InternalState", typeof(object),
            typeof(NullableCheckbox), new PropertyMetadata(null, InternalStateChanged));
        private static void InternalStateChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            (d as NullableCheckbox).IsChecked2 = (bool?)e.NewValue;
        }

        public object IsChecked2
        {
            get { return (object)GetValue(IsChecked2Property); }
            set { SetValue(IsChecked2Property, value); }
        }
        public static readonly DependencyProperty IsChecked2Property =
            DependencyProperty.Register("IsChecked2", typeof(object),
            typeof(NullableCheckbox), new PropertyMetadata(null, IsChecked2Changed));
        private static void IsChecked2Changed(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var checkbox = (d as NullableCheckbox);
            bool? newvalue = null;
            if (e.NewValue is bool?)
                newvalue = (bool?)e.NewValue;
            else if (e.NewValue != null)
            {
                bool newbool;
                if (!bool.TryParse(e.NewValue.ToString(), out newbool))
                    return;
                newvalue = newbool;
            }
            if (!checkbox.IsChecked.Equals(newvalue))
                checkbox.IsChecked = newvalue;
        }
    }
}
